<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="formHandleEvent"
          >
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-selectSupplier>
              <el-button :disabled="!canSelectSupplier" @click="selectSupplier"
                >添加供应商</el-button
              >
            </template>
            <template v-slot:filter-removeSupplier>
              <el-button
                :disabled="!(tableInfo.selections.length && !orderId)"
                @click="removeSupplier"
                >删除供应商</el-button
              >
            </template>
          </page-filter>
          <div>
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :tab-index="false"
                :check-box="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-evaluateItemScore="scope">
                  <el-form-item
                    :prop="`data.${scope.$index}.evaluateItemScore_${
                      scope.childIndex
                    }_${scope.index - 1}`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: scope.$index >= 0,
                              message: '请输入分值',
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      style="width: 100%; margintop: 18px"
                      v-model="
                        scope.row[
                          `evaluateItemScore_${scope.childIndex}_${
                            scope.index - 1
                          }`
                        ]
                      "
                      clearable
                      controls-position="right"
                      :precision="2"
                      :min="0"
                      :max="scope.childItem.itemScore"
                      @change="
                        onchange(
                          $event,
                          scope.$index,
                          scope.childItem,
                          scope.column,
                          scope.childIndex,
                          scope.index,
                          scope.row
                        )
                      "
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-remark="scope">
                  <el-form-item :prop="`data.${scope.$index}.remark`">
                    <el-input
                      v-model.lazy="scope.row.remark"
                      :maxlength="200"
                      clearable
                    />
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 选择供应商 -->
    <select-supplier-modify
      v-if="supplierInfo.visible"
      v-model:showDialog="supplierInfo.visible"
      :highlightRow="true"
      :query="supplierInfo.query"
      @callback="callBackSupplier"
    />
  </div>
</template>
<script setup name="evaluationRecordModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import PageFilter from '@/components/PageFilter/index'
import {
  selectEvaluatedSupplier,
  getEnabledEvaluateTemplate,
  getEvaluateTemplateById,
  getEvaluateRecordById,
  updateEvaluateRecord,
  batchInsertEvaluateRecord,
} from '@/api/evaluate.js'
import SelectSupplierModify from '@/components/SelectSupplier/index'
import moment from 'moment'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'orderId', 'title', 'tableRow'])

const formRefs = ref('')
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})
const formInfo = reactive({
  ref: null,
  data: {
    updateUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
  },
  fieldList: [
    {
      label: '评价人',
      value: 'updateUserName',
      type: 'input',
      disabled: true,
    },
    {
      label: '评价部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '评价体系',
      value: 'evaluateTemplateName',
      type: 'input',
      disabled: true,
    },
    {
      label: '年度',
      value: 'evaluateYear',
      type: 'date',
      dateType: 'year',
      valueFormat: 'YYYY',
      event: 'evaluateYear',
    },
    {
      label: '期间类型',
      value: 'periodType',
      type: 'select-model',
      code: 'period_type',
      event: 'periodType',
    },
    {
      label: '评价期间',
      value: 'periodValue',
      type: 'select-model',
      code: 'half_year',
      show: true,
      event: 'periodValue',
    },
  ],
  rules: {
    evaluateYear: [
      {
        required: true,
        message: '请选择年度',
        trigger: 'change',
      },
    ],
    evaluateTemplateName: [
      {
        required: true,
        message: '请选择评价体系',
        trigger: 'blur',
      },
    ],
    periodType: [
      {
        required: true,
        message: '请选择期间类型',
        trigger: 'change',
      },
    ],
    periodValue: [
      {
        required: true,
        message: '请选择评价期间',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {},
  list: [
    {
      type: 'slot',
      label: '添加供应商',
      value: 'selectSupplier',
    },
    {
      type: 'slot',
      label: '删除供应商',
      value: 'removeSupplier',
    },
  ],
})
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  details: [],
  data: [],
  selections: [],
  classifyFieldList: [],
  fieldList: [
    { label: '供应商', value: 'supplierName' },
    {
      label: '合计',
      value: 'totalScore',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'slot',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeSupplier,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})

const supplierInfo = reactive({
  visible: false,
  query: {
    supplierIdNotIn: '',
    supplierAuth: 'supplierId',
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSelectSupplier = computed(() => {
  return (
    formInfo.data.evaluateYear &&
    formInfo.data.periodValue &&
    formInfo.data.periodType &&
    !props.orderId
  )
})
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      val.forEach((item) => {
        let evaluateItemScore = 0
        item.details.forEach((el, index, arr) => {
          let evaluateClassifyScore = 0

          arr.forEach((i) => {
            if (i.classifyName === el.classifyName) {
              evaluateClassifyScore = proxy.$fn.accAdd(
                evaluateItemScore,
                i.evaluateItemScore || 0
              )
            }
          })
          el.evaluateClassifyScore = evaluateClassifyScore

          evaluateItemScore = proxy.$fn.accAdd(
            evaluateItemScore,
            el.evaluateItemScore || 0
          )
        })
        item['totalScore'] = evaluateItemScore
      })
    }
  },
  {
    deep: true,
  }
)
watch(
  () => formInfo.data.evaluateYear,
  (val) => {
    if (Number(formInfo.data.periodType) === 1) {
      formInfo.data.periodValue = val
    }
  }
)
watch(
  () => formInfo.data.periodType,
  (val) => {
    let month = moment(new Date()).format('M')
    if (Number(val) === 1) {
      //期间类型取值为年度时，隐藏评价期间输入框，评价期间值为年度输入框的值
      showFieldListItem(false, 'periodValue')
      formInfo.data.periodValue = formInfo.data.evaluateYear
    } else if (Number(val) === 2) {
      //期间类型为半年度时，取值为上半年、下半年，默认为上半年；
      showFieldListItem(true, 'periodValue')
      formInfo.data.periodValue = 1
      formInfo.fieldList.forEach((item) => {
        if (item.value === 'periodValue') {
          item.code = 'half_year'
        }
      })
    } else if (Number(val) === 3) {
      //期间类型为季度时，取值为1~4季度，缺省为当前所在季度减一，
      //但最底为第一季度（如当前为2月，缺省值为1季度，当前为4月，
      //缺省值为1季度，当前为8月，缺省为2季度）
      showFieldListItem(true, 'periodValue')
      formInfo.fieldList.forEach((item) => {
        if (item.value === 'periodValue') {
          item.code = 'quarter'
        }
      })

      if (
        month === '1' ||
        month === '2' ||
        month === '3' ||
        month === '4' ||
        month === '5' ||
        month === '6'
      ) {
        formInfo.data.periodValue = 1
      } else if (month === '7' || month === '8' || month === '9') {
        formInfo.data.periodValue = 2
      } else if (month === '10' || month === '11' || month === '12') {
        formInfo.data.periodValue = 3
      }
    } else if (Number(val) === 4) {
      //期间类型为月度时，取值为1~12月份，缺省为当前月份减一，最低为1月，
      //（如当前为1月，缺省为1月，当前为2月，缺省为1月，当前为12月，缺省为11月）
      showFieldListItem(true, 'periodValue')
      formInfo.fieldList.forEach((item) => {
        if (item.value === 'periodValue') {
          item.code = 'month'
        }
      })
      if (month === '1') {
        formInfo.data.periodValue = 1
      } else {
        formInfo.data.periodValue = Number(month) - 1
      }
    }
  },
  {
    deep: true,
  }
)
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  if (props.orderId) {
    disabledFieldListItem(true, 'evaluateYear')
    disabledFieldListItem(true, 'periodType')
    disabledFieldListItem(true, 'periodValue')
    tableInfo.handle.btList[0].show = false
    getMain()
  } else {
    getTemplate()
  }
})

function disabledFieldListItem(disabled, nameValue) {
  let fieldList = formInfo.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.disabled = disabled
    }
  })
}
function onchange(e, $index, column, _column, childIndex, i, tableRow) {
  tableInfo.data.forEach((row, rowIndex) => {
    if (row.supplierId === tableRow.supplierId) {
      proxy.$refs.tableForm.clearValidate(
        `data.${$index}.evaluateItemScore_${childIndex}_${i - 1}`
      )
    }

    if ($index === rowIndex) {
      row.details.forEach((item) => {
        let str = `${item.itemName}(${item.itemScore})分`
        if (str === column.label && column.classifyName === item.classifyName) {
          item['evaluateItemScore'] = e
        }
      })
    }
  })
}

function getTemplate() {
  getEnabledEvaluateTemplate().then((res) => {
    if (res && res.success) {
      formInfo.data['evaluateTemplateName'] = res.data.templateName
      formInfo.data['evaluateTemplateId'] = res.data.id
      getTableField(res.data.id)
    }
  })
}
function getTableField(id) {
  getEvaluateTemplateById(id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data.classifyDetails
      tableInfo.classifyFieldList = data.map((item) => {
        let obj = {
          label: `${item.classifyName}(${item.classifyScore})分`,
          type: 'multiHeader',
          children: [],
        }
        obj.children = item.itemDetails.map((el) => {
          tableInfo.details.push({
            evaluateClassifyName: item.classifyName,
            evaluateClassifyScore: 0,
            evaluateItemName: el.itemName,
            evaluateItemScore: 0,
            classifyName: item.classifyName,
            classifyScore: item.classifyScore,
            itemName: el.itemName,
            itemScore: el.itemScore,
          })
          return {
            label: `${el.itemName}(${el.itemScore})分`,
            value: `evaluateItemScore`,
            type: 'slot',
            classifyName: item.classifyName,
            evaluateItemName: el.itemName,
            itemScore: el.itemScore,
            width: '180px',
          }
        })
        return obj
      })
      let arr1 = [{ label: '供应商', value: 'supplierName' }]
      let arr2 = [
        {
          label: '合计',
          value: 'totalScore',
        },
        {
          label: '备注',
          value: 'remark',
          type: 'slot',
        },
      ]
      tableInfo.fieldList = arr1.concat(tableInfo.classifyFieldList, arr2)
    }
  })
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}

function formHandleEvent() {
  tableInfo.data = []
}

function selectSupplier() {
  // 供应商
  let query = {}
  let ids = []
  query.evaluateYear = formInfo.data.evaluateYear
  query.periodType = formInfo.data.periodType
  query.periodValue = formInfo.data.periodValue
  query.deptId = proxy.$store.state.user.userInfo.dept
    ? proxy.$store.state.user.userInfo.dept.id
    : ''
  selectEvaluatedSupplier(query).then((res) => {
    if (res && res.success) {
      ids = res.data
    }
    if (tableInfo.data.length) {
      tableInfo.data.forEach(function (item) {
        ids.push(item.supplierId)
      })
    }
    supplierInfo.query.supplierIdNotIn = String(ids)
    supplierInfo.visible = true
  })
}
function callBackSupplier(data) {
  if (data && data.length) {
    data.forEach((item) => {
      item.details = proxy.$fn.deepClone(tableInfo.details)
    })
    tableInfo.data = tableInfo.data.concat(data)
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = undefined
    if (props.orderId) {
      api = updateEvaluateRecord
    } else {
      api = batchInsertEvaluateRecord
    }
    let arr = []

    tableInfo.data.forEach((item) => {
      arr.push({
        ...formInfo.data,
        totalScore: item.totalScore,
        supplierName: item.supplierName,
        supplierId: item.supplierId,
        remark: item.remark,
        details: item.details,
      })
    })
    let params = props.orderId ? arr[0] : arr
    api(params).then((res) => {
      if (res && res.success) {
        emit('returnModify')
        showDialog.value = false
      }
    })
  })
}

function removeSupplier(selectRow = undefined) {
  if (selectRow && selectRow.supplierId) {
    tableInfo.data = tableInfo.data.filter((row) => row !== selectRow)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter(
          (row) => !tableInfo.selections.includes(row)
        )
      })
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}

function getMain() {
  getEvaluateRecordById(props.orderId).then((res) => {
    if (res && res.success) {
      getTableField(res.data.evaluateTemplateId)
      setTimeout(() => {
        formInfo.data = res.data
        tableInfo.data = [res.data]
        tableInfo.data[0].details = tableInfo.data[0].details.map(
          (row, rowIndex) => {
            row = {
              ...tableInfo.details[rowIndex],
              ...row,
            }

            tableInfo.classifyFieldList.forEach((item, index) => {
              item.children.forEach((el, elIndex) => {
                if (
                  row.evaluateItemName === el.evaluateItemName &&
                  row.evaluateClassifyName === el.classifyName
                ) {
                  tableInfo.data[0][`evaluateItemScore_${elIndex}_${index}`] =
                    row.evaluateItemScore
                }
              })
            })
            return row
          }
        )
      }, 1000)
    }
  })
}
</script>
